﻿/*  
 *  IIS LogFile Analyser, Copyright (C) 2013. http://www.iis-analyser.com
 *  --
 *  This program is free software, provided "AS IS" WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE
 * 
 *  File Author: Ian Quigley,    2013-02-23
 */


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using Web.Common;
using System.Globalization;

namespace Web.Filter
{
    public class FilterDateRange : IFilterView
    {
        public string Name
        {
            get { return "Filter Date Range"; }
        }

        public void BuildHtml(StringBuilder html, string sqlColumn)
        {
            html.Append( "<td align='right' width='20%'><b>Date Range</b></td><td width='80%'><div data-sqlcolumn='" + sqlColumn + "' data-filtertype='FilterDateRange'>" +
                "From: <input type='text' class='datePicker filterChange' id='dateStart' />&nbsp;&nbsp;" +
                "To: <input type='text' class='datePicker filterChange' id='dateEnd' />" + 
                "</div></td>");
        }


        public string UpdateSql( string sql, FilterItem item )
        {
            if (string.IsNullOrWhiteSpace( item.Data) )
                return sql;

            var parts = item.Data.Trim().Split( ' ' );
            if (parts.Length != 2)
                return sql;

            DateTime start, end;
            if ( DateTime.TryParseExact( parts[0], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out start ) &&
                 DateTime.TryParseExact( parts[1], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out end ))
            {
                sql = sql.Replace( "{" + item.SqlColumn + "}", string.Format( "({0} > '{1:yyyy-MM-dd}' AND {0} < '{2:yyyy-MM-dd}') ", item.SqlColumn, start, end ), StringComparison.OrdinalIgnoreCase );
            }

            return sql;
        }
    }
}